package com.server.llh.llhserverwork.activity.server;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.ServerNetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;

import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseNFCActivity;

import com.server.llh.llhserverwork.adapter.LLHServerCateAdapter;
import com.server.llh.llhserverwork.adapter.LLHShoppingServerAdapter;
import com.server.llh.llhserverwork.adapter.ServerMenuAdapter;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.ProCateService;
import com.server.llh.llhserverwork.bean.SerInitProPackage;
import com.server.llh.llhserverwork.bean.ShowProInfoBean;

import com.server.llh.llhserverwork.port.ClearViewDataInterface;
import com.server.llh.llhserverwork.port.OptionServerInterface;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.ServerStatementData;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.ShopUploadParamJson;
import com.server.llh.llhserverwork.utils.ShoppingServerCar;
import com.server.llh.llhserverwork.utils.ToastTool;
import com.server.llh.llhserverwork.view.ShowProInfoView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-07-14.
 */

public class LlhServerOptionActivity extends LlhBaseNFCActivity implements OptionServerInterface, ClearViewDataInterface {
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.title_view)
    LinearLayout titleView;
    @BindView(R.id.menu_two_lv)
    ListView menuTwoLv;
    @BindView(R.id.menu_content_lv)
    ListView menuContentLv;
    @BindView(R.id.noDataSrc)
    ImageView noDataSrc;
    @BindView(R.id.noData)
    RelativeLayout noData;
    @BindView(R.id.center)
    LinearLayout center;
    @BindView(R.id.center_view)
    LinearLayout centerView;
    @BindView(R.id.shop_main)
    RelativeLayout shopMain;
    private final static String TAG = "MenuTwo";
    private String mCateId, mCateLevel, mCateName, mIsPack;
    private String orgId, chainId, orgTypeId, userId;

     private List<SerInitProPackage> serviceInitProPack = new ArrayList<SerInitProPackage>();//服务项显示数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        chainId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.CHAIN_ID, getApplicationContext());
        orgTypeId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE, getApplicationContext());
        orgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID, getApplicationContext());
        userId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID, getApplicationContext());
        LlhOptionSubOrderActivity.registCallBack(this);
        Intent intent = getIntent();
        if (intent != null) {
            mCateName = intent.getStringExtra("cateName");
            mCateId = intent.getStringExtra("cateId");
            mCateLevel = intent.getStringExtra("cateLevel");
            mIsPack = intent.getStringExtra("mIsPack");
            titleName.setText(mCateName);
        }
        menuTwoLv.setVisibility(View.GONE);
        menuContentLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (serviceInitProPack.get(position) != null) {
                    ShowProInfoBean showProInfoBean = new ShowProInfoBean(serviceInitProPack.get(position).getPictureUrl(),
                            serviceInitProPack.get(position).getPrice(), serviceInitProPack.get(position).getPackName(),
                            serviceInitProPack.get(position).getReamark(), "100%");
                    ShowProInfoView.showProInfo(showProInfoBean, LlhServerOptionActivity.this.findViewById(R.id.shop_main), LlhServerOptionActivity.this);
                }
            }
        });

        reqServerMenu(mCateId, mIsPack);
    }

    /**
     * 服务二级分类请求
     *
     * @param mCateId
     * @param mIsPack
     */
    private void reqServerMenu(final String mCateId, final String mIsPack) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("cateLevel", 1);
        lRequest.addParam("parendId", mCateId);
        lRequest.addParam("cateId", mCateId);
        lRequest.addParam("packorgId", SharedPreferenceUtil.getUserInfo(Constants.UserInfo.CHAIN_ID, getApplicationContext()));
        lRequest.addParam("packorgTypeId", 3);
        lRequest.addParam("isPack", mIsPack);
        lRequest.addParam("isEmptyShow", Constants.IS_EMPTY_SHOW_INT);
        lRequest.addParam("packStatus", Constants.PACK_STATUS_INT);
        lRequest.addParam("isPro", "2");
        lRequest.setUri(ServerPort.GET_SERVER_ON_TYPE);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        lRequest.setType(String.class);

        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {

                T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
            }

            @Override
            public void onNext(String responseBean, String code) {
                if ("200".equals(code) && !"[]".equals(responseBean) && responseBean != null) {
                    service = new Gson().fromJson(responseBean.toString(),
                            new TypeToken<List<ProCateService>>() {
                            }.getType());
                    if (service != null && service.size() > 0) {

                        centerView.setVisibility(View.VISIBLE);
                        menuTwoLv.setVisibility(View.VISIBLE);
                        llhServerAdapter = new ServerMenuAdapter(getApplicationContext(), service);
                        menuTwoLv.setAdapter(llhServerAdapter);
                        menuTwoLv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {

                            @Override
                            public void run() {

                                menuTwoLv.setSelected(true);
                                menuTwoLv.setSelection(0);
                                menuTwoLv.setItemChecked(0, true);
                                menuTwoLv.performItemClick(menuTwoLv.getChildAt(0), 0, 0);
                            }
                        }, 500);
                    } else {

                    }
                } else {

                }
            }
        });
        menuTwoLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mCateIds = service.get(position).getCateId();
                int mIsPack = service.get(position).getIsPack();
                reqServerCateMenu(mCateIds, mIsPack);
            }
        });

    }

    long mCateIds;
    private LLHServerCateAdapter llhServerCateContentAdapter = null;//右侧服务项adapter
    private ServerMenuAdapter llhServerAdapter = null;
    private List<ProCateService> service = new ArrayList<>();
    private ArrayList<SerInitProPackage> shopping_car_List = new ArrayList<>();//购物车显示list数据

    /**
     * 服务项请求
     *
     * @param mCateId
     * @param mIsPack
     */
    public void reqServerCateMenu(long mCateId, int mIsPack) {
        LRequest lRequest = new LRequest();
        if (mIsPack == 1) {
            lRequest.addParam("serviceCateId", mCateId);
        } else {
            lRequest.addParam("detailCateId", mCateId);
        }
        if ("3".equals(orgTypeId)) {
            lRequest.addParam("orgId", orgId);
            lRequest.addParam("orgTypeId", orgTypeId);
        } else {
            lRequest.addParam("orgId", chainId);
            lRequest.addParam("orgTypeId", "3");
            lRequest.addParam("supplierId", orgId);
            lRequest.addParam("supplierType", "4");
        }
        lRequest.addParam("isPro", 2);
        lRequest.setUri(ServerPort.SERVER_JSON_DATA);
        lRequest.setIp(UrlsTools.SERVER_REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {

                T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null && Constants.SER_RESPON_SUCC_CODE.equals(code)) {
                    serviceInitProPack = new Gson().fromJson(
                            responseBean.toString(),
                            new TypeToken<List<SerInitProPackage>>() {
                            }.getType());
                    if (serviceInitProPack != null && serviceInitProPack.size() > 0) {

                        menuContentLv.setVisibility(View.VISIBLE);
                        if (menuContentLv.getAdapter() == null) {
                            llhServerCateContentAdapter = new LLHServerCateAdapter(getApplicationContext(), serviceInitProPack);
                            menuContentLv.setAdapter(llhServerCateContentAdapter);
                            llhServerCateContentAdapter.registerCallBack(LlhServerOptionActivity.this);
                        } else {
                            llhServerCateContentAdapter.setListData(serviceInitProPack);
                            llhServerCateContentAdapter.notifyDataSetChanged();
                        }
                    }
                } else {
                    T.showAnimToast(getApplicationContext(), "抱歉，暂时没有该服务！");
                }
            }
        });
    }
    @Override
    public void showProgress() {
        try {
            showProgress(getApplicationContext());
        } catch (Exception e) {
        }
    }
    @Override
    protected INetRequestManager getRequestManager() {
        return ServerNetRequestManager.getInstance();
    }
    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception e) {
        }
    }

    @Override
    protected int getlayout() {
        return R.layout.llh_option_server;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }

    @OnClick(R.id.main_back)
    public void onViewClicked() {
        onBackPressed();
    }

    @Override
    public void callBack(SerInitProPackage serInitProPackage) {

        if (serInitProPackage != null && serInitProPackage.getIsPro() == 2 && mCateIds == 3) {
            showMyDilog(serInitProPackage);
        } else {
            int num = ShoppingServerCar.getShopingData(serInitProPackage, shopping_car_List);
            Log.d(TAG, "num==" + num + "getPackId===" + serInitProPackage.getPackId() + "getPrice===" + serInitProPackage.getPrice());
            if (shopping_car_List != null && shopping_car_List.size() > 0) {
                reqServerShopUpload(shopping_car_List);
            }
        }

    }

    AlertDialog alertDialog = null;

    public void showDialog(final SerInitProPackage SerInitProPackage) {

        LayoutInflater inflater = (LayoutInflater) LlhServerOptionActivity.this.getSystemService(LAYOUT_INFLATER_SERVICE);
        final View view = inflater.inflate(R.layout.my_dialog_task, null);
        alertDialog = new AlertDialog.Builder(LlhServerOptionActivity.this).setTitle("请输入金额:").setIcon(android.R.drawable.ic_dialog_info).setView(view).setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                SerInitProPackage serInitProPackagea = SerInitProPackage;
                EditText nameEditText = (EditText) view.findViewById(R.id.editText1);
                String username = nameEditText.getText().toString();
                if ("".equals(username) || "0".equals(username)) {
                    ToastTool.showText(getApplicationContext(), "输入金额不能为0!");
                    return;
                } else {
                    serInitProPackagea.setPrice(Double.valueOf(username));
                    Log.d(TAG, "serInitProPackage111==" + serInitProPackagea.getPrice());
                    int num = ShoppingServerCar.getShopingData(serInitProPackagea, shopping_car_List);
                 Log.d(TAG,"num=="+num);
                    if (shopping_car_List != null && shopping_car_List.size() > 0) {
                        reqServerShopUpload(shopping_car_List, Double.valueOf(username));
                    }
                }
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                Toast.makeText(LlhServerOptionActivity.this, "您取消了购买临时服务", Toast.LENGTH_LONG).show();
            }
        }).show();
    }

    public static ServerStatementData serverStatementData;

    public void reqServerShopUpload(List<SerInitProPackage> serInitProPackageList) {
        String reqServerParamJson = ShopUploadParamJson.reqServerParamJson(serInitProPackageList);
        try {
            reqServerParamJson = URLEncoder.encode(reqServerParamJson, "utf-8");
            LRequest lRequest = new LRequest();
            lRequest.addParam("userId", userId);
            lRequest.addParam("serOrderInfoDetailList", reqServerParamJson);
            lRequest.addParam("orgId", orgId);
            lRequest.addParam("orgTypeId", orgTypeId);
            lRequest.addParam("cateLevel", Constants.CATE_LEVEL_INT);
            lRequest.addParam("isPro", "2");
            lRequest.setUri(ServerPort.SERVER_CAL_ORDER_MONEY);
            lRequest.setIp(UrlsTools.SERVER_REQ_URL);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null && Constants.SER_RESPON_SUCC_CODE.equals(code)) {
                        Log.d(TAG, "responseBean==" + responseBean.toString());
                        serverStatementData = new Gson().fromJson(responseBean.toString(), ServerStatementData.class);
                        if (serverStatementData != null) {
                            Log.d(TAG, "serverStatementData==" + serverStatementData.getSerOrderInfo().getAmountPayable());
                            Intent intent = new Intent(getApplicationContext(), LlhOptionSubOrderActivity.class);
                            startActivity(intent);
                        }
                    } else {
                        T.showAnimToast(getApplicationContext(), "暂时没有服务信息！");
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    public static ServerStatementData serverStatementData2;

    public void reqServerShopUpload(List<SerInitProPackage> serInitProPackageList, final double price) {
        Log.d(TAG, " serInitProPackageList.get(0).getPrice()==" + serInitProPackageList.get(0).getPrice());
        String reqServerParamJson = ShopUploadParamJson.reqServerParamJson(serInitProPackageList);
        try {
            reqServerParamJson = URLEncoder.encode(reqServerParamJson, "utf-8");
            LRequest lRequest = new LRequest();
            lRequest.addParam("userId", userId);
            lRequest.addParam("serOrderInfoDetailList", reqServerParamJson);
            lRequest.addParam("orgId", orgId);
            lRequest.addParam("orgTypeId", orgTypeId);
            lRequest.addParam("cateLevel", Constants.CATE_LEVEL_INT);
            lRequest.setUri(ServerPort.SERVER_CAL_ORDER_MONEY);
            lRequest.setIp(UrlsTools.SERVER_REQ_URL);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if (responseBean != null && Constants.SER_RESPON_SUCC_CODE.equals(code)) {
                        Log.d(TAG, "responseBean-==" + responseBean);
                        serverStatementData2 = new Gson().fromJson(responseBean.toString(), ServerStatementData.class);
                        if (serverStatementData2 != null) {
                            serverStatementData2.getSerOrderInfoDetailBeanList().get(0).getSerOrderInfoDetail().setPrice(price);
                            serverStatementData2.getSerOrderInfo().setAmountPayable(price);
                            serverStatementData = serverStatementData2;
                            Intent intent = new Intent(getApplicationContext(), LlhOptionSubOrderActivity.class);
                            intent.putExtra("price", price);
                            startActivity(intent);
                        }
                    } else {
                        T.showAnimToast(getApplicationContext(), "暂时没有服务信息！");
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void clearShopData(String succ) {
        if ("0".equals(succ)) {
        } else {
            Intent intent = new Intent();
            intent.setAction(Constants.BroadCastAction.FINISH_ALL_ACTIVITY);
            sendBroadcast(intent);
            finish();
        }
    }
    @Override
    public void refreshData() {
    }

    public void showMyDilog(final SerInitProPackage SerInitProPackage) {
        final SerInitProPackage serInitProPackagea = SerInitProPackage;
        final AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(LlhServerOptionActivity.this);    // 系统默认Dialog没有输入框
        final AlertDialog tempDialog = alertDialog.create();
        View alertDialogView = View.inflate(LlhServerOptionActivity.this, R.layout.llh_my_dialog, null);
        final EditText et_dialog = (EditText) alertDialogView.findViewById(R.id.editText1);
        final EditText teskEditText = (EditText) alertDialogView.findViewById(R.id.editText2);

        setPoint(et_dialog);
        Button btn_dialog_resolve = (Button) alertDialogView.findViewById(R.id.quit_btn);
        btn_dialog_resolve.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (tempDialog!=null){
                    tempDialog.dismiss();
                    Toast.makeText( LlhServerOptionActivity.this, "您取消了购买临时服务", Toast.LENGTH_LONG).show();
                }
            }
        });
        Button btn_dialog_cancel = (Button) alertDialogView.findViewById(R.id.ok_btn);
        btn_dialog_cancel.setOnClickListener  (new View.OnClickListener() {
            public void onClick(View v) {
                String username = et_dialog.getText().toString();
                String teskText=teskEditText.getText().toString();
                if ("".equals(username) ) {
                    ToastTool.showText(getApplicationContext(), "输入金额不能为0!");
                    return;
                } else {
                    if (teskText!=null&&!"".equals(teskText)){
                        serInitProPackagea.setReamark(teskText);
                        serInitProPackagea.setPackName(teskText);
                    }else{
                        serInitProPackagea.setReamark("临时服务");
                        serInitProPackagea.setPackName("临时服务");
                    }
                    if(username.matches("[^\\.]*\\.[^\\.]*")){
                        serInitProPackagea.setPrice(Double.valueOf(username));
                        Log.d(TAG, "serInitProPackage111==" + serInitProPackagea.getPrice());
                        int num = ShoppingServerCar.getShopingData(serInitProPackagea, shopping_car_List);
                        Log.d(TAG,"num=="+num);
                        if (shopping_car_List != null && shopping_car_List.size() > 0) {
                            reqServerShopUpload(shopping_car_List, Double.valueOf(username));
                        }
                    }else{
                        T.showAnimToast(getApplicationContext(),"数据格式不正确，含有多个小数点");
                    }
                }
                if (tempDialog!=null){
                    tempDialog.dismiss();
                }
            }
        });
        tempDialog.setView(alertDialogView, 0, 0, 0, 0);
        tempDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            public void onShow(DialogInterface dialog) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et_dialog, InputMethodManager.SHOW_IMPLICIT);
            }
        });

        tempDialog.show();
    }
    private static final int DECIMAL_DIGITS = 2;//小数的位数
    public static void setPoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > DECIMAL_DIGITS) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + DECIMAL_DIGITS + 1);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                } else {
                    editText.setText(s + ".00");
                    editText.setSelection(1);
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,int after) {
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }
}
